package com.datree.cache_server.framework.interceptor;


import com.datree.cache_server.framework.hodler.HeaderContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.util.ContentCachingRequestWrapper;
import org.springframework.web.util.ContentCachingResponseWrapper;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

@Component
@Slf4j
public class HeaderInterceptor implements HandlerInterceptor {

    private int order = Ordered.LOWEST_PRECEDENCE - 8;
    public static final String SPLIT_STRING_M = "=";
    public static final String SPLIT_STRING_DOT = ", ";

    /**
     * 获取请求地址上的参数
     *
     * @param request
     * @return
     */
    public static String getRequestParams(HttpServletRequest request) {
        StringBuilder sb = new StringBuilder();
        Enumeration<String> enu = request.getParameterNames();
        //获取请求参数
        while (enu.hasMoreElements()) {
            String name = enu.nextElement();
            sb.append(name + SPLIT_STRING_M).append(request.getParameter(name));
            if (enu.hasMoreElements()) {
                sb.append(SPLIT_STRING_DOT);
            }
        }
        return sb.toString();
    }


    /**
     * 打印请求参数
     *
     * @param request
     */
    private String getRequestBody(HttpServletRequest request) throws IOException {
        if (request.getInputStream() != null && request.getContentLength() > 0) {
            byte[] buf = new byte[request.getContentLength()];
            request.getInputStream().read(buf);
            if (buf.length > 0) {
                String payload;
                try {
                    payload = new String(buf, 0, buf.length, request.getCharacterEncoding());
                } catch (UnsupportedEncodingException e) {
                    payload = "[unknown]";
                }
                return payload.replaceAll("\\n", "");
            }
        }
        return "";
    }

    /**
     * 打印返回参数
     *
     * @param response
     */
    private String getResponseBody(ContentCachingResponseWrapper response) {
        ContentCachingResponseWrapper wrapper = WebUtils.getNativeResponse(response,
                ContentCachingResponseWrapper.class);
        if (wrapper != null) {
            byte[] buf = wrapper.getContentAsByteArray();
            if (buf.length > 0) {
                String payload;
                try {
                    payload = new String(buf, 0, buf.length, wrapper.getCharacterEncoding());
                } catch (UnsupportedEncodingException e) {
                    payload = "[unknown]";
                }
                return payload;
            }
        }
        return "";
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        log.info("\n接收到接口请求：requestURL = [{}], timestamp = [{}], method = [{}], queryString = [{}], contentType = [{}]",
//                request.getRequestURL(), simpleDateFormat1.format(new Date()), request.getMethod(), request.getQueryString(), request.getContentType());


//        String urlParams = getRequestParams(request);
//        log.info("\n接收到接口url参数：requestURL = [{}] , timestamp = [{}], params = [{}]",request.getRequestURL(),simpleDateFormat1.format(new Date()), urlParams);
//        if (request.getContentType() != null && request.getContentType().equals("application/json")) {
//            ContentCachingRequestWrapper wrapperRequest = new ContentCachingRequestWrapper(request);
//            String requestBodyStr = getRequestBody(wrapperRequest);
//            log.info("\n接收到接口Body参数: requestBody = [{}]", requestBodyStr);
//        }


//        String tenantId = request.getHeader("tenantId");
//        if ((tenantId == null || tenantId.isEmpty()) && request.getParameterMap() != null && request.getParameterMap().containsKey("tenantId")) {
//            tenantId = request.getParameter("tenantId");
//        }
//
//        if (tenantId != null && !tenantId.isEmpty()) {
//            HeaderContextHolder.setTenantId(Long.parseLong(tenantId));
//        }
//
//        String studentId = request.getHeader("studentId");
//
//        if ((studentId == null || studentId.isEmpty()) && request.getParameterMap() != null && request.getParameterMap().containsKey("studentId")) {
//
//            studentId = request.getParameter("studentId");
//        }
//
//        if (studentId != null && !studentId.isEmpty()) {
//            HeaderContextHolder.setStudentId(Long.parseLong(studentId));
//        }
        return true;
    }
}
